import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import createPersistedState from "vuex-persistedstate"
import SecureLS from "secure-ls"

Vue.use(Vuex)

// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})

/**
 * @description 设置vuex数据持久化，默认储存全部数据，通过配置参数储存所需要的数据;通过SecureLS进行加密
 */
const ls = new SecureLS({ isCompression: false })
const vuexPersisted = createPersistedState({
  storage: { // 自定义storage储存方法
    getItem: key => ls.get(key),
    setItem: (key, value) => ls.set(key, value),
    removeItem: key => ls.remove(key)
  },
  // paths: ['user'], // 配置储存模块，注意：1.不能添加permission模块，否则动态添加路由会出错！！！2.不能与reducer同时存在
  /**
   * @description 配置需要持久化的数据
   */
  reducer (state) {
    return {
      user: {
        userInfo: state.user.userInfo
      },
      market: {
        gasInfo: state.market.gasInfo
      },
      vipPool: {
        id: state.vipPool.id
      },
      permission: {
        menuType: state.permission.menuType,
        hasMarketRight: state.permission.hasMarketRight
      }
    }
  }
})

export default new Vuex.Store({
  modules,
  getters,
  plugins: [vuexPersisted]
})
